package com.hxgis.oc.product.idw;

import com.hxgis.oc.config.OConfig;
import com.hxgis.oc.util.ds.FileDatabase;
import com.hxgis.oc.util.ds.FileRecord;
import com.hxgis.oc.util.idw.IDWConvertor;
import com.hxgis.oc.product.file.DownloadTask;
import com.hxgis.oc.product.base.ProduceTask;
import com.hxgis.oc.product.base.ProductFactory;
import lombok.Getter;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.List;

@Component
public class IDWProductManager extends ProductFactory {
    @Getter
    private static final String factoryName = "idw";

    public IDWProductManager() {
        super(factoryName, OConfig.getConfig().getProductIDW(),2);
    }

    @Override
    protected void clearExpired(String dataSet, long expiredTime) {
        if(expiredTime == 0){
            return;
        }

        FileDatabase fileDatabase = getFileDatabase(dataSet);
        if(fileDatabase == null){
            return;
        }

        List<FileRecord> list = fileDatabase.select(dataSet,null,expiredTime);
        for(FileRecord record : list)
        {
            String rawFileName = record.getFileName();
            File file = fileDatabase.getFile(dataSet,rawFileName);
            IDWConvertor idwConvertor = new IDWConvertor(file);
            idwConvertor.clear();
        }

        fileDatabase.deleteExpired(dataSet, expiredTime);
    }

    private void addConvertTaskIfSet(DownloadTask task){
        IDWConvTask convTask = (IDWConvTask) task.getConvertTask(IDWConvTask.class);
        if(convTask == null)
        {
            return;
        }

        convTask.setInputFile(task.getOutputFile());
        addConvTask(convTask,String.valueOf(task.getFileID()));
    }

    @Override
    protected void onPublish(ProduceTask o) {
        String ds = o.getDataSet();
        if(!accept(ds)){
            return;
        }

        if(DownloadTask.class == o.getClass()){
            addConvertTaskIfSet((DownloadTask)o);
        } else if(IDWConvTask.class == o.getClass()){
            submit(o);
        }
    }

    @Override
    protected void onRetrieve(ProduceTask o) {

    }
}
